﻿using LPLS.CollectionHardProtocol.OPCUAModules.OPCUARuleJudgeModule;
using LPLS.DBEntities.ConfigModels.AlarmModels.AlarmVarableCodeRuleConfigModels;
using LPLS.DBEntities.ConfigModels.DeviceInfoModels;
using LPLS.DBEntities.DataCollectionModels;
using LPLS.DBEntities.OEEModule.OEEModels.DataStatisticModels;
using LPLS.DBInterface.ConfigModels.DataCollectionConfigModule.DataCollectionRuleEdgeModule;
using LPLS.DBInterface.ConfigModels.DataCollectionConfigModule.PLC;
using LPLS.DBInterface.ConfigModels.DeviceInfoModels;
using LPLS.DBInterface.DataCollectionModels;
using LPLS.DBInterface.OEEModule.OEEModels.DataStaticsticModels;
using LPLS.RuleEngineBaseCommon.CollectionVarRuleEngineModule;
using Masuit.Tools;
using Masuit.Tools.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using Timer = System.Timers.Timer;

namespace LPLS.DataCollection.Service
{
    public class DataCollectionOP
    {
        IDataCollectionRuleConfigService _dataCollectionRuleConfigService;
        IPLCVarPropertyConfigService _pLCVarPropertyConfigService1;
        IDataCollectionOPCUAConfigService _dataCollectionOPCUAConfigService;
        IDataCollectionRecordService _recordService;
        IDataCollectionRecordTempService _tempRecordService;
      

        public void Init() 
        {
            _deviceInfoService = Program.ServiceProvider.GetService<IDeviceBaseInfoService>();        
            _OeeCompentService = Program.ServiceProvider.GetService<ICompentDataStatisticsService>();// OeeTubeService;
            _recordService = Program.ServiceProvider.GetService<IDataCollectionRecordService>();// recordService;
            _tempRecordService = Program.ServiceProvider.GetService<IDataCollectionRecordTempService>();// tempRecordService;
            _pLCVarPropertyConfigService1 = Program.ServiceProvider.GetService<IPLCVarPropertyConfigService>();// pLCVarPropertyConfigService;
            _dataCollectionOPCUAConfigService = Program.ServiceProvider.GetService<IDataCollectionOPCUAConfigService>();// dataCollectionOPCUAConfigService;
            _dataCollectionRuleConfigService = Program.ServiceProvider.GetService<IDataCollectionRuleConfigService>();// dataCollectionRuleConfigService;

            CollectionVarRuleEngineEvent.OnColletionVarRuleEngineEvent += CollectionVarRuleEngineEvent_OnColletionVarRuleEngineEvent;

        }



        /// <summary>
        /// 接收到PLC数据后  临时表更新状态
        /// </summary>
        /// <param name="arg1"></param>
        /// <param name="arg2"></param>
        /// <param name="arg3"></param>
        /// <param name="arg4"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void CollectionVarRuleEngineEvent_OnColletionVarRuleEngineEvent(Commons.Enums.StatusEnum status, Guid deviceid, Guid compentid, List<DBEntities.ConfigModels.DataCollectionConfigModule.DataCollectionType.PLC.PLCVarPropertyConfig> plcVars)
        {
            DateTime nowtime = DateTime.Now;
          
           
            var tempRecordList = _tempRecordService.GetData().Where(e=>e.DeviceId==deviceid&&e.CompentId==compentid).ToList();
            if (tempRecordList.Count > 0) //里面有数据
            {
                var tempmodel=tempRecordList.FirstOrDefault();
               
                var tempststus = tempRecordList.FirstOrDefault().Status;
                if (status!=tempststus)//状态变了 入库record表
                {

                    DataCollectionRecord model=new DataCollectionRecord ();
                    model.Status = tempststus;
                    model.StartTime = tempmodel.CollectionTime;
                    model.EndTime = nowtime;
                    model.DeviceId = deviceid;
                    model.CompentId = compentid;
                    model.IsCollection = 0;
                    _recordService.AddData(model);
                    //修改temp数据
                    tempmodel.CollectionTime = nowtime;
                    tempmodel.Status = status;
                    _tempRecordService.UpdateData(tempmodel);
                }
            }

            else
            { //没数据的时候就应该增加数据了
                DataCollectionRecordTemp model= new DataCollectionRecordTemp ();
                model.Status = status;
                model.CollectionTime = nowtime;
                model.DeviceId = deviceid;
                model.CompentId = compentid;             
                _tempRecordService.AddData(model);

               
            }



          
        }

        static List<OPCUARuleJudgeDTO> AllComponeList = new List<OPCUARuleJudgeDTO>();


      
        public    void LoadData()
        {
            DeviceBaseInfos= _deviceInfoService.GetData();
            var oPCUACollectionData = _dataCollectionOPCUAConfigService.GetData();
            ///先获取到所有的变量
            var data = _pLCVarPropertyConfigService1.GetData().GroupBy(e => e.ComponentID).ToList();
            foreach (var item in data)
            {

                ///找到相应的OPCUA连接
                var compentOpuacollData = oPCUACollectionData.Where(e => e.CompentID == item.Key).ToList();
                if (compentOpuacollData.Count > 0)
                {
                    var workflowli = _dataCollectionRuleConfigService.GetData().Where(e => e.CompentID == item.Key).ToList();

                    if (workflowli.Count == 0)
                    {
                        LogManager.Info($"部件ID:{item.Key} 下未能找到相应的规则配置 请在配置软件中进行配置  该部件的数据将不会进行采集");
                        continue;

                    }
                    var workflowmodel = workflowli.FirstOrDefault();

                    var singleCompentOpcuaModel = compentOpuacollData.FirstOrDefault();
                    ///创建相应的实例
                    OPCUARuleJudgeDTO dto = new OPCUARuleJudgeDTO(singleCompentOpcuaModel.Url);
                    dto.CompentID = item.Key;
                    dto.PLCVarList = new List<DBEntities.ConfigModels.DataCollectionConfigModule.DataCollectionType.PLC.PLCVarPropertyConfig>(item);
                    dto.DeviceID = singleCompentOpcuaModel.DeviceID;
                    dto.OPCUAID = singleCompentOpcuaModel.ID;
                    dto.OPCUAName = singleCompentOpcuaModel.OPCUAName;

                    dto.JsonName = workflowmodel.WorkFlowName + ".json";
                    dto.Url = singleCompentOpcuaModel.Url;
                    foreach (var item2 in item)
                    {
                        dto.Nodes.Add(item2.VarAddress);
                    }
                    AllComponeList.Add(dto);
                }
                else
                {

                    LogManager.Info($"部件ID:{item.Key} 未能找到相应的连接 请在配置软件中进行配置  该部件的数据将不会进行采集");


                }
            }
        }

        /// <summary>
        /// 开始数据采集了
        /// </summary>
        public     void StartOP() 
        {
            if (AllComponeList.Count>0)
            {

                OPCUARuleJudgeOP model = new OPCUARuleJudgeOP(AllComponeList, 50);
                model.BatchRead();

            }
            else
            {
                LogManager.Info("没有任何OPCUA连接 或者配置 ");
            }
        }


        public static bool IsReStart = false;
        public void ReLoadData() 
        {

            if (IsReStart) {

                var oPCUACollectionData = _dataCollectionOPCUAConfigService.GetData();
                ///先获取到所有的变量
                var data = _pLCVarPropertyConfigService1.GetData().GroupBy(e => e.ComponentID).ToList();
                foreach (var item in data)
                {

                    ///找到相应的OPCUA连接
                    var compentOpuacollData = oPCUACollectionData.Where(e => e.CompentID == item.Key).ToList();
                    if (compentOpuacollData.Count > 0)
                    {
                        var workflowli = _dataCollectionRuleConfigService.GetData().Where(e => e.CompentID == item.Key).ToList();

                        if (workflowli.Count == 0)
                        {
                            LogManager.Info($"部件ID:{item.Key} 下未能找到相应的规则配置 请在配置软件中进行配置  该部件的数据将不会进行采集");
                            continue;

                        }
                        var workflowmodel = workflowli.FirstOrDefault();

                        var singleCompentOpcuaModel = compentOpuacollData.FirstOrDefault();
                        ///创建相应的实例
                        OPCUARuleJudgeDTO dto = new OPCUARuleJudgeDTO(singleCompentOpcuaModel.Url);
                        dto.CompentID = item.Key;
                        dto.PLCVarList = new List<DBEntities.ConfigModels.DataCollectionConfigModule.DataCollectionType.PLC.PLCVarPropertyConfig>(item);
                        dto.DeviceID = singleCompentOpcuaModel.DeviceID;
                        dto.OPCUAID = singleCompentOpcuaModel.ID;
                        dto.OPCUAName = singleCompentOpcuaModel.OPCUAName;

                        dto.JsonName = workflowmodel.WorkFlowName + ".json";
                        dto.Url = singleCompentOpcuaModel.Url;
                        foreach (var item2 in item)
                        {
                            dto.Nodes.Add(item2.VarAddress);
                        }
                        AllComponeList.Add(dto);
                    }
                    else
                    {

                        LogManager.Info($"部件ID:{item.Key} 未能找到相应的连接 请在配置软件中进行配置  该部件的数据将不会进行采集");


                    }
                }
            }
        
        }


        #region 数据采集后的结果

        ICompentDataStatisticsService _OeeCompentService;

        IDeviceBaseInfoService _deviceInfoService;
        public static List<DeviceBaseInfo> DeviceBaseInfos { get; private set; }=new List<DeviceBaseInfo> ();

        public  void DealCollectionData() 
        {
         
                var devidemodel = DeviceBaseInfos;

                var data = _recordService.GetData(100);
                List<int> recordidList = new List<int>();
                List<CompentDataStatistics> li = new List<CompentDataStatistics>();
                List<DeviceDataStatistic> devideli = new List<DeviceDataStatistic>();


            foreach (var item in data)
            {
                recordidList.Add(item.Id);
                TimeSpan totaltime = item.EndTime - item.StartTime;
                CompentDataStatistics model = new CompentDataStatistics();
                model.StartTime = item.StartTime;
                model.EndTime = item.EndTime;
                model.Status = item.Status;
                model.TotalSecondTime = (int)totaltime.TotalSeconds;
                model.DeviceID = item.DeviceId;
                model.CompentId = item.CompentId;
                li.Add(model);
            }
            try
            {
                var res = _OeeCompentService.AddData(li);
                if (res > 0)
                {
                    var result = _recordService.UpdateData(recordidList);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

               
            
          
          
        }
        #endregion

    }
}
